package com.ibm.hannover.development.tools.configurations;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.internal.launching.EEVMInstall;
import org.eclipse.jdt.internal.launching.EEVMType;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.VMStandin;
import org.eclipse.jdt.launching.environments.ExecutionEnvironmentDescription;

public class EEVMConfiguration extends VMConfiguration {

	private static final String CLAZZ = EEVMConfiguration.class.getName();
	private static final Logger logger = Logger.getLogger(CLAZZ);
	
	private static final String AUTO_GENERATED_NAME = "AutoGeneratedDEE";
	private static final String EEVM = "org.eclipse.jdt.launching.EEVMType";
	
	public EEVMConfiguration(String path, boolean isDefault) {
		super(path, isDefault, EEVM);
	}
	
	protected final void fillVMFields(IVMInstall vm) {
		File dir = new File(jrePath + File.separatorChar + "jre"
				+ File.separatorChar + "default.ee");
		try {
			vm.setInstallLocation(dir.getCanonicalFile());
		} catch (IOException e) {
			vm.setInstallLocation(dir.getAbsoluteFile());
		}
		vm.setName(AUTO_GENERATED_NAME);
		vm.setJavadocLocation(detectJavadocLocation());
		IVMInstall newVM;
		try {
			newVM = JavaRuntime.createVMFromDefinitionFile(dir, vm.getName(),
					vm.getId());
			// set properties
			VMStandin vv = (VMStandin) newVM;
			File eeFile = dir;
			File home = null;
			if (eeFile != null) {
				vv.setAttribute(EEVMInstall.ATTR_DEFINITION_FILE, eeFile.getPath());
				ExecutionEnvironmentDescription description = new ExecutionEnvironmentDescription(eeFile);
				String homePath = description.getProperty(ExecutionEnvironmentDescription.JAVA_HOME);
				if (homePath != null) {
					home = new File(homePath);
					try {
						home = home.getCanonicalFile();
					} catch (IOException e) {
					}
				}
			}
			vv.setInstallLocation(home);
			this.newVM = vv;
		} catch (CoreException e) {
			logger.logp(Level.WARNING, CLAZZ, "fillVMFields", "Failed to create EE vm.");
		}

	}

	public final String getGeneratedVMName() {
		return AUTO_GENERATED_NAME;
	}

}
